'use strict';

/**
 * Redis 推送订阅
 */
const redis = require('redis');
const globalConfig = require('../../config/global_config');
const redisOptions = globalConfig.redis;
const logger = require('../utils/logger');

let client;

function init() {
    client = redis.createClient(redisOptions);
    // 客户端连接redis成功后执行回调
    client.on("ready", function () {
        // logger.logInfo("\n" + '===== Redis client connect success' + "\n");
        console.log('[redis] redis connect success');
    });

    client.on("error", function (error) {
        logger.logError("\n" + '===== Redis Error - ' + error + "\n");
    });

    client.on("end", function () {
        console.log('[redis] redis disconnect');
    });
}

function quit() {
    if (client) {
        client.quit();
    }
}

/**
 * 推送订阅
 * @param channel,message
 */
function publish(channel, message) {
    message = JSON.stringify(message);
    logger.logInfo("\n" + '===== Redis publish - channel: ' + channel +
        ', message: ' + message + ' =====' + "\n");
    if (client && channel && message) {
        client.publish(channel, message);
    }
}


exports.init = init;
exports.quit = quit;
exports.publish = publish;
